package solution.liuyu2783.offer;

import solution.liuyu2783.common.ListNode;

/**
 * 剑指 Offer 22. 链表中倒数第k个节点
 * 输入一个链表，输出该链表中倒数第k个节点。为了符合大多数人的习惯，本题从1开始计数，即链表的尾节点是倒数第1个节点。
 */
public class Q22_KthInNode_E {

    //循环
    public static ListNode getKthFromEnd(ListNode head, int k) {
        ListNode temp = head;
        int s = 0;
        while (temp != null) {
            temp = temp.next;
            s++;
        }
        ListNode temp1 = head;
        int i = 0;
        while (temp1 != null) {
            if(i == s-k){
                return temp1;
            }
            temp1 = temp1.next;
            i++;
        }
        return null;
    }

    //快慢指针
    public static ListNode twoPointer(ListNode head, int k) {
        ListNode faster = head;
        ListNode later = head;
        //移动faster到位置k
        while(k > 0){
            faster = faster.next;
            k--;
        }
        //同时移动双指针，当faster走到末尾。later就是倒数k个
        while (faster !=null){
            faster = faster.next;
            later = later.next;
        }
        return later;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        ListNode node7 = new ListNode(7);
        ListNode node8 = new ListNode(8);
        ListNode node9 = new ListNode(9);
        ListNode node10 = new ListNode(10);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;
        node7.next = node8;
        node8.next = node9;
        node9.next = node10;
        ListNode kthFromEnd = Q22_KthInNode_E.twoPointer(node1, 2);
        System.out.println(kthFromEnd.val);
    }
}
